Plus One

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

Solution:

  1. public class Solution {
  2. public int[] plusOne(int[] digits) {
  3. int n = digits.length, i = n - 1;
  4. for (; i >= 0; i--) {
  5. if (digits[i] == 9) {
  6. digits[i] = 0;
  7. } else {
  8. digits[i]++;
  9. return digits;
  10. }
  11. }
  12. int[] res = new int[n + 1];
  13. res[0] = 1;
  14. return res;
  15. }
  16. }